package com.ruoyi.common.utils;

import cn.hutool.json.JSONUtil;
import com.aliyun.oss.*;
import com.aliyun.oss.model.PutObjectResult;
import com.obs.services.ObsClient;
import com.ruoyi.common.utils.file.FileUploadUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

public class OssUtil {

    // endpoint以杭州为例，其它region请按实际情况填写。simple-mall.oss-cn-beijing.aliyuncs.com
    private static final String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    private static final String accessKeyId = "LTAI5tFMChM8vZoNHi1kX5xs";
    private static final String accessKeySecret = "j9SK49ar6pqAUyW9PegrMDTYtXqIWt";
    private static final String bucketName = "yuedou";


	private static final String endpointObs = "http://obs.cn-north-9.myhuaweicloud.com";
	private static final String accessKeyIdObs = "HPUARHTZGR5VUUX5JADZ";
	private static final String accessKeySecretObs = "hVP7cXcZzbLgNbEMeX23ZGG0Cic5IyIGRLtwwLCY";
	private static final String bucketNameObs = "caihengyun";


	private static final int validity = 60 * 1000;


    public static void main(String[] args){
        String url = "/article/1/2c1157af-7612-43bd-b34c-e928338ab6a9.png";
        url = url.substring(1);
        boolean bl = deleteObjByKey(url);
        if(bl){
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }
    }

    /**
     * 上传文件
     * @param inputStream 要上传的文件流
     * @param fileName 要上传的文件名字
     * @param upload_type 要上传的文件类型
     */
    public static boolean upload(InputStream inputStream,String fileName,int upload_type) {
        boolean ret = false;
        // 上传文件流
        if (inputStream!=null){
			OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //inputStream = new FileInputStream("/Users/ran/Desktop/会议记录0521.txt");
            String prefix = FileUploadUtils.getUploadPrefix(upload_type);
			System.out.println("文件路径：" + prefix + fileName);
            if (prefix!=null){
				try{
					PutObjectResult putObjectResult = ossClient.putObject(bucketName, prefix + fileName, inputStream);
					String eTag = putObjectResult.getETag();
					System.out.println("upload " + prefix + fileName +"-->"+ eTag);

				} catch (OSSException oe) {
					System.out.println("Caught an OSSException, which means your request made it to OSS, "
						+ "but was rejected with an error response for some reason.");
					System.out.println("Error Message:" + oe.getErrorMessage());
					System.out.println("Error Code:" + oe.getErrorCode());
					System.out.println("Request ID:" + oe.getRequestId());
					System.out.println("Host ID:" + oe.getHostId());
				} catch (ClientException ce) {
					System.out.println("Caught an ClientException, which means the client encountered "
						+ "a serious internal problem while trying to communicate with OSS, "
						+ "such as not being able to access the network.");
					System.out.println("Error Message:" + ce.getMessage());
				}
            }
            // 关闭client。
            ossClient.shutdown();
			System.out.println("upload "+ prefix + fileName +"是否成功-->"+ (ret?"YES":"NO"));
        }
        return ret;
    }

    /**
     * 上传文件
     * @param inputStream 要上传的文件流
     * @param fileName 要上传的文件名字
     */
    public static boolean upload(InputStream inputStream,String fileName) {
        boolean ret = false;
        // 上传文件流
        if (inputStream!=null){
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            //inputStream = new FileInputStream("/Users/ran/Desktop/会议记录0521.txt");
//            String prefix = getUploadPrefix(upload_type);
            if (fileName!=null){
                PutObjectResult putObjectResult = ossClient.putObject(bucketName, fileName, inputStream);
                String eTag = putObjectResult.getETag();
                System.out.println("upload "+fileName +"-->"+ eTag);
            }
            // 关闭client。
            ossClient.shutdown();
        }
        System.out.println("upload "+fileName +"是否成功-->"+ (ret?"YES":"NO"));
        return ret;
    }



	/**
	 * 上传文件
	 * @param inputStream 要上传的文件流
	 * @param fileName 要上传的文件名字
	 * @param upload_type 要上传的文件类型
	 */
	public static boolean uploadObs(InputStream inputStream, String fileName, int upload_type) {
		boolean ret = false;
		// 上传文件流
		if (inputStream != null){
			ObsClient ossClient = new ObsClient(accessKeyIdObs, accessKeySecretObs, endpointObs);
			//inputStream = new FileInputStream("/Users/ran/Desktop/会议记录0521.txt");
			String prefix = FileUploadUtils.getUploadPrefix(upload_type);
			if (prefix != null){
				System.out.println("上传图片地址：" + prefix + fileName);
				com.obs.services.model.PutObjectResult putObjectResult = ossClient.putObject(bucketNameObs, prefix + fileName, inputStream);
				System.out.println("上传OBS  = " +JSONUtil.parseObj(putObjectResult).toString());
				//上传OBS  = {"bucketName":"caihengyun",
				// "objectUrl":"http://caihengyun.obs.cn-north-9.myhuaweicloud.com:80/product%2F2025%2F07%2F22%2Ffbd301f9-df0c-4578-a7c1-4cdd44a32d41.jpg",
				// "originalHeaders":{"date":"Tue, 22 Jul 2025 07:08:56 GMT","x-obs-id-2":"36AAAUgAIAABAAAQAAEAABAAAQAAEAABAAAaI=AAAAAAAAAAAAAAAAAAAAAAAAAA",
				// "content-length":"0","server":"OBS","x-obs-request-id":"0000019830F6CA34080737EB0E45A885","connection":"keep-alive",
				// "etag":"\"cc89b57d4fc1c2ebd70ffe3a427a5623\""},
				// "responseHeaders":{"date":1753168136000,"content-length":"0","server":"OBS","request-id":"0000019830F6CA34080737EB0E45A885",
				// "id-2":"36AAAUgAIAABAAAQAAEAABAAAQAAEAABAAAaI=AAAAAAAAAAAAAAAAAAAAAAAAAA","connection":"keep-alive","etag":"\"cc89b57d4fc1c2ebd70ffe3a427a5623\""},
				// "objectKey":"product/2025/07/22/fbd301f9-df0c-4578-a7c1-4cdd44a32d41.jpg","etag":"\"cc89b57d4fc1c2ebd70ffe3a427a5623\"","statusCode":200}
				String eTag = putObjectResult.getEtag();
				System.out.println("upload "+fileName +"-->"+ eTag);
			}
			// 关闭client。
			try {
				ossClient.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		System.out.println("upload "+fileName +"是否成功-->"+ (ret?"YES":"NO"));
		return ret;
	}


	/**
     * 根据key获取url
     * @param object_key
     * @return
     */
    public static String getSignUrl(String object_key){
        //创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId,accessKeySecret);
        //validity url的有效期
        URL url = ossClient.generatePresignedUrl(bucketName, object_key, new Date(new Date().getTime()+validity));
		//关闭client
        ossClient.shutdown();
        return url==null?null:url.toString();
    }


    /**
     * 删除文件
     * @param objKey
     * @return
     */
    public static boolean deleteObjByKey(String objKey) {
        boolean ret = false;
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
        ossClient.deleteObject(bucketName,objKey);
        // Object是否存在。
        ret = ossClient.doesObjectExist(bucketName, objKey);
        ossClient.shutdown();
        return !ret;
    }

    public static BufferedImage getImageInfoByUrl(String urlStr){

        try{
            URL url = new URL(urlStr);
            URLConnection urlConnection = url.openConnection();
            int length = urlConnection.getContentLength();
            System.out.print("length: " + length);
            if(length == -1){
                System.out.print("image not exist");
            }else{
                BufferedImage sourceImg = ImageIO.read(url);
                System.out.print("image width:" + sourceImg.getWidth());
                System.out.print("image height:" + sourceImg.getHeight());
                return sourceImg;
            }
        }catch (MalformedURLException e){
//            logger.info("url not right " + e.getMessage(), e);
        } catch (IOException e){
//            logger.info("IOException " + e.getMessage(), e);
        }
        return null;
    }
}
